import axios from "axios";
import { getStorage, removeStorage } from '@/utils/storage';
import {useMessage} from '@/hooks/message';
import router from '@/router';

const message = useMessage()

const service = axios.create({
  baseURL: 'http://192.168.1.31:3000',
  timeout: 50000, // request timeout
});


service.interceptors.request.use(
  (config) => {

    const token = getStorage('token')
    config.headers['authorization'] = `Bearer ${token}`
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


service.interceptors.response.use(
  (response) => {
    if (response.status == 200) {
        const data = response.data

        if (data.code !== 200) {
            message.wraning(data.msg)
        }
        // token 过期
        if (data.code == 403) {
          router.replace({path: '/login', query: {}})
          removeStorage('token')
          removeStorage('user')
        }
        
        return data
    } else {
        return response;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const getRequest = (config) => service({ method: 'get', ...config })

export const postRequest = (config) => service({ method: 'post', ...config })

export const putRequest = (config) => service({ method: 'put', ...config })

export const delRequest = (config) => service({ method: 'delete', ...config })